class RemoteStore
{
    getHost()
    {
        let config = JSON.parse(localStorage.getItem('config'));
        // return 'http://namelist.axfree.com';
        return config.remoteStore.url;
    }

    async get(key)
    {
        let promise = await this.request(this.getHost() + '/get.php?key=' + key);
        let resp = await promise.json();
        return resp;
    }

    async save(data)
    {
        /**
         * {
         *  key: 111,
         *  user: bbb,
         *  ver: cc
         * }
         */
        let options = {
            method: 'post',
            body: JSON.stringify(data)
        };
        let promise = await this.request(this.getHost() + '/add.php', options);
        let resp = await promise.json();
        return resp;
    }

    async list()
    {
        let promise = await this.request(this.getHost() + '/get.php');
        let resp = await promise.json();
        return resp;
    }

    sync()
    {
        let status = false;
        let resp = this.list();
            resp.then(function(response){
                if (response.status) {
                    status = response.status;
                    let ticketList = {};
                    response.data.forEach(function(item, key){
                        ticketList[item.key] = item.user;
                    });
                    // if get data update to local
                    Logger.debug('Update Tickets length', Object.keys(ticketList).length);
                    if (Object.keys(ticketList).length) {
                        Logger.debug('Update Tickets', ticketList);
                        ticketList = remoteStore.merge(ticketList);
                        Logger.debug('list' , ticketList);
                        localStorage.setItem('jira-tickets', JSON.stringify(ticketList));
                    }
                }
            })
        
        return status;
    }

    merge(list)
    {
        let localList = JSON.parse(localStorage.getItem('jira-tickets'));
        window.localList = localList;
        if (Object.keys(localList).length) {
            Object.keys(localList).forEach(function(key){
                list[key] = localList[key];
            }); 
        }

        return list;
    }

    request(url, options)
    {
         return requestJs.fetch(url, options);
    }
}
window.remoteStore = new RemoteStore();